"""
通用Pydantic模式
定义API响应的通用结构
"""
from typing import Any, Dict, List, Optional, Generic, TypeVar
from pydantic import BaseModel, Field

T = TypeVar('T')


class BaseResponse(BaseModel):
    """基础响应模式"""
    success: bool = True
    message: str = "操作成功"
    timestamp: Optional[str] = None


class MessageResponse(BaseResponse):
    """消息响应模式"""
    pass


class StatusResponse(BaseResponse):
    """状态响应模式"""
    status_code: int = 200


class DataResponse(BaseResponse, Generic[T]):
    """数据响应模式"""
    data: T


class ListResponse(BaseResponse, Generic[T]):
    """列表响应模式"""
    data: List[T]
    total: int = 0


class PaginatedResponse(BaseResponse, Generic[T]):
    """分页响应模式"""
    data: List[T]
    total: int = 0
    page: int = 1
    page_size: int = 20
    total_pages: int = 0
    
    def __init__(self, **data):
        super().__init__(**data)
        if self.total > 0 and self.page_size > 0:
            self.total_pages = (self.total + self.page_size - 1) // self.page_size


class ErrorResponse(BaseModel):
    """错误响应模式"""
    success: bool = False
    message: str
    error_code: Optional[str] = None
    details: Optional[Dict[str, Any]] = None
    timestamp: Optional[str] = None


class ValidationErrorResponse(ErrorResponse):
    """验证错误响应模式"""
    validation_errors: List[Dict[str, Any]] = []


# 分页查询参数
class PaginationParams(BaseModel):
    """分页参数"""
    page: int = Field(default=1, ge=1, description="页码")
    page_size: int = Field(default=20, ge=1, le=100, description="每页数量")
    
    @property
    def offset(self) -> int:
        """计算偏移量"""
        return (self.page - 1) * self.page_size


# 排序参数
class SortParams(BaseModel):
    """排序参数"""
    sort_by: str = Field(default="created_at", description="排序字段")
    sort_order: str = Field(default="desc", regex="^(asc|desc)$", description="排序方向")


# 搜索参数
class SearchParams(BaseModel):
    """搜索参数"""
    keyword: Optional[str] = Field(default=None, description="关键词")
    filters: Dict[str, Any] = Field(default_factory=dict, description="过滤条件")